import 'package:async/async.dart';
import 'package:boss/color_constant.dart';

import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/calendar_bar.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:router/annotation.dart';
import 'package:flustars/flustars.dart' as flustars;

@RouterConfig(OperationPage.pageName)
class OperationPage extends StatefulWidget {
  static const pageName = '/OperationPage';

  @override
  _State createState() => _State();
}

class _State extends State<OperationPage> with SingleTickerProviderStateMixin {
  final GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();

  RefreshController _refreshController;

  DateTime startTime;

  DateTime endTime;

  List<Map> _tabs = [
    {'name': '订单数', 'id': 0},
    {'name': '金额', 'id': 1},
  ];
  PageController mPageController;

  //当前页面在在第几个tab
  int tableIndex = 0;

  List dataListArr0 = [
    {"title": '反结账订单数', "value": '${0}单'},
    {"title": '撤单数', "value": '${0}单'},
    {"title": '退单数', "value": '${0}单'},
    {"title": '免单数', "value": '${0}单'},
    {"title": '退菜数', "value": '${0}单'},
    {"title": '赠菜数', "value": '${0}单'},
    {"title": '清零钟费次数', "value": '${0}次'},
  ];

  List dataListArr1 = [
    {"title": '反结账订单金额', "value": '¥${AmountUtil.price2String(0)}'},
    {"title": '退单金额', "value": '¥${AmountUtil.price2String(0)}'},
    {"title": '免单金额', "value": '¥${AmountUtil.price2String(0)}'},
    {"title": '退菜金额', "value": '¥${AmountUtil.price2String(0)}'},
    {"title": '赠菜金额', "value": '¥${AmountUtil.price2String(0)}'},
    {"title": '清零钟费金额', "value": '¥${AmountUtil.price2String(0)}'},
  ];

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: false);
    mPageController = PageController(initialPage: tableIndex);

    final now = DateTime.now();

    startTime = DateUtils.startOfTheDay(now);
    endTime = DateUtils.endOfTheDay(now);
  }

  @override
  void dispose() {
    mPageController.dispose();
    _refreshController.dispose();
    super.dispose();
  }

  Widget tabContent() {
    return Container(
      child: Column(
        children: <Widget>[
          ListAssembly(
            dataList: tableIndex == 0 ? dataListArr0 : dataListArr1,
          ),
        ],
      ),
    );
  }

  Widget line() {
    return Container(
      decoration: BoxDecoration(
        color: Color.fromRGBO(87, 112, 246, .6),
        borderRadius: BorderRadius.circular(
          16.w,
        ),
      ),
      width: 70.w,
      height: 12.w,
    );
  }

  String dateTime2String(DateTime dateTime) {
    return flustars.DateUtil.formatDate(dateTime);
  }

  Future<Result<List<dynamic>>> refreshTask() async {
    if (tableIndex == 0) {
      var res = await api.statSensitiveOrderCount(
        startTime: dateTime2String(startTime),
        endTime: dateTime2String(endTime),
      );
      if (res.successful()) {
        var resData = res.data;
        dataListArr0 = [
          {"title": '反结账订单数', "value": '${resData["oppositeOrderCount"] ?? 0}单'},
          {"title": '撤单数', "value": '${resData["unOrderCount"] ?? 0}单'},
          {"title": '退单数', "value": '${resData["backOrderCount"] ?? 0}单'},
          {"title": '免单数', "value": '${resData["freeOrderCount"] ?? 0}单'},
          {"title": '退菜数', "value": '${resData["backFoodCount"] ?? 0}单'},
          {"title": '赠菜数', "value": '${resData["giveFoodCount"] ?? 0}单'},
        ];
        setState(() {});
        return Result.value([1]);
      } else {
        toast(res.msg);
        return Result.value([1]);
      }
    } else {
      var res = await api.statSensitiveOrderAmount(
        startTime: dateTime2String(startTime),
        endTime: dateTime2String(endTime),
      );
      if (res.successful()) {
        var resData = res.data;
        dataListArr1 = [
          {"title": '反结账订单金额', "value": '¥${AmountUtil.price2String((resData["oppositeOrderAmount"]) ?? 0)}'},
          {"title": '退单金额', "value": '¥${AmountUtil.price2String((resData["backOrderAmount"]) ?? 0)}'},
          {"title": '免单金额', "value": '¥${AmountUtil.price2String((resData["freeOrderAmount"]) ?? 0)}'},
          {"title": '退菜金额', "value": '¥${AmountUtil.price2String((resData["backFoodAmount"]) ?? 0)}'},
          {"title": '赠菜金额', "value": '¥${AmountUtil.price2String((resData["giveFoodAmount"]) ?? 0)}'},
        ];
        setState(() {});
        return Result.value([1]);
      } else {
        toast(res.msg);
        return Result.value([1]);
      }
    }
  }

  Future<Result<List<dynamic>>> loadTask() async {
    return Result.value([]);
  }

  refresh({bool needMove = true}) async {
    await _refreshController.requestRefresh(
      needMove: needMove,
      duration: Duration(milliseconds: 100),
    );
  }

  @override
  Widget build(BuildContext context) {
    return LoaderPullRefresh<dynamic>(
        key: loaderPullRefreshKey,
        loadTask: loadTask,
        refreshTask: refreshTask,
        builder: (context) {
          return Container(
            padding: EdgeInsets.symmetric(
              horizontal: 30.w,
            ),
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(
                      top: 26.w,
                      bottom: 8.w,
                    ),
                    child: CalendarBar(
                      startDateTime: startTime,
                      endDateTime: endTime,
                      onDateTimeChanged: (List<DateTime> dateTime) {
                        startTime = dateTime[0];
                        endTime = dateTime[1];
                        loaderPullRefreshKey.currentState.refresh();
                      },
                      type: CalendarType.ymdhm,
                    ),
                  ),
                  Container(
                    height: 78.w,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: (_tabs ?? [])
                          .map((str) => GestureDetector(
                                onTap: () {
                                  if (str["id"] == tableIndex) {
                                    return;
                                  }
                                  tableIndex = str["id"];
                                  loaderPullRefreshKey.currentState.refresh();
                                  setState(() {});
                                },
                                child: Container(
                                    width: 300.w,
                                    color: Colors.white,
                                    child: Stack(
                                      alignment: AlignmentDirectional.bottomCenter,
                                      children: <Widget>[
                                        Center(
                                          child: Text(
                                            "${str["name"]}",
                                            style: tableIndex == str["id"] ? TextStyleConstant().normal_1_34 : TextStyleConstant().normal_3_28,
                                          ),
                                        ),
                                        if (tableIndex == str["id"])
                                          Positioned(
                                            bottom: 18.w,
                                            child: line(),
                                          ),
                                      ],
                                    )),
                              ))
                          .toList(),
                    ),
                  ),
                  tabContent(),
                ],
              ),
            ),
          );
        });
  }
}

class ItemAssembly extends StatelessWidget {
  String title;
  String value;

  ItemAssembly({Key key, this.title, this.value}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(
        vertical: 38.w,
      ),
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(
        width: 1.px,
        color: ColorConstant.e6e6,
      ))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            "${title ?? '--'}",
            style: TextStyleConstant().normal_1_28,
          ),
          Text(
            "${value ?? '--'}",
            style: TextStyleConstant().normal_2_26,
          ),
        ],
      ),
    );
  }
}

//订单数和金额list
class ListAssembly extends StatelessWidget {
  List dataList;

  ListAssembly({Key key, this.dataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: (dataList ?? [])
          .map((str) => Container(
                child: ItemAssembly(
                  title: '${str["title"]}',
                  value: '${str["value"]}',
                ),
              ))
          .toList(),
    );
  }
}
